import axios from 'axios'
import store from '@/store/index.js'
import {Modal, notification} from 'ant-design-vue'
const http = {}

var instance = axios.create({
    timeout: 5000,
    validateStatus(status) {
        switch (status) {
        case 400:
            this.$message.error('请求出错');
            break
        case 401:
            this.$message.error('授权失败，请重新登录');
            store.commit('LOGIN_OUT')
            setTimeout(() => {
                window.location.reload()
            }, 1000)
            return
        case 403:
            notification.error({message: '系统提示', description: '拒绝访问', duration: 4})
            break
        case 404:
            notification.error({message: '系统提示', description: '很抱歉，资源未找到!', duration: 4})
            break
        case 500:
            this.$message.warning('服务端错误');
            break
        }
        return status >= 200 && status < 300
    }
})

// 添加请求拦截器
instance.interceptors.request.use(
    config => {
        // const token = Vue.ls.get(ACCESS_TOKEN)
        if (config.data && config.data.TOKEN) {
            try {
                config.data = {
                    data: encrypt(JSON.stringify(config.data), config.data.TOKEN), sign: config.data.TOKEN
                }
            } catch (e) {
                // console.info(e)
            }
        }
        config.headers['TOKEN'] = localStorage.getItem('token')
        return config;
    },
    err => {
        return Promise.reject(err);
    }
)

// 响应拦截器即异常处理
instance.interceptors.response.use(
    response => {
        // dataAxios 是 axios 返回数据中的 data
        const dataAxios = response.data
        // 这个状态码是和后端约定的
        const {status, code} = dataAxios
        if(code == 0){
          return dataAxios
        }
        // 根据 code 进行判断
        // return dataAxios;
        if (status == 0) {
            // 如果没有 code 代表这不是项目后端开发的接口 比如可能是 D2Admin 请求最新版本
            return dataAxios.data
        } else {
            return Promise.reject(dataAxios.msg)
        }
    },
    error => {
        return Promise.reject(error)   // 返回接口返回的错误信息
    },
)

http.get = function(url, options) {
    return new Promise((resolve, reject) => {
        instance
            .get(url, options)
            .then(response => {
                if (response.code === 0) {
                    resolve(response.data)
                } else {
                    reject(response.msg)
                }
            })
            .catch(e => {
                console.log(e)
            })
    })
}

http.post = function(url, data, options) {
    return new Promise((resolve, reject) => {
        instance
            .post(url, data, options)
            .then(response => {
                if (response.code === 0) {
                    resolve(response.data)
                } else {
                    reject(response.message)
                }
            })
            .catch(e => {
                console.log(e)
            })
    })
}

export default http
